using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace CGF
{
    public static class TouchHelper
    {
        private static Dictionary<string, PointerEventData> eventSystemObjs = new Dictionary<string, PointerEventData>();
        private static List<RaycastResult> raycastResults = new List<RaycastResult>();
        private static EventSystem eventSystem;

        /// <summary>
        /// 是否点在UI上(PC平台不传参数，移动平台传fingerId)
        /// </summary>
        public static bool IsTouchOnUI(int fingerId = 0)
        {
            if (Application.isMobilePlatform)
            {
                EventSystem.current.IsPointerOverGameObject(fingerId);
            }
            return EventSystem.current.IsPointerOverGameObject();
        }

        /// <summary>
        /// 是否点击在指定的UI上
        /// </summary>
        public static bool IsTouchOnUI(GameObject target, Vector2 screenPos)
        {
            List<RaycastResult> results = GetTouchAllUI(screenPos);
            for (int i = 0; i < results.Count; i++)
            {
                GameObject go = results[i].gameObject;
                if (go.activeInHierarchy && go == target)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取当前点击位置的所有UI
        /// </summary>
        public static List<RaycastResult> GetTouchAllUI(Vector2 screenPos)
        {
            string currSceneName = SceneManager.GetActiveScene().name;
            PointerEventData pointerEventData;
            if (!eventSystemObjs.ContainsKey(currSceneName))
            {
                pointerEventData = new PointerEventData(GameObject.FindObjectOfType<EventSystem>());
                eventSystemObjs.Add(currSceneName, pointerEventData);
            }
            else
            {
                pointerEventData = eventSystemObjs[currSceneName];
            }
            pointerEventData.pressPosition = screenPos;
            pointerEventData.position = screenPos;
            EventSystem.current.RaycastAll(pointerEventData, raycastResults);
            return raycastResults;
        }

        public static bool IsGlobalTouchEnable
        {
            get
            {
                eventSystem ??= GameObject.Find("EventSystem")?.GetComponent<EventSystem>();
                return eventSystem ? eventSystem.enabled : false;
            }
        }

        public static void SetGlobalTouchEnable(bool b)
        {
            Debug.Log($"[B]SetGlobalTouchEnable {b}");
            eventSystem ??= GameObject.Find("EventSystem")?.GetComponent<EventSystem>();
            if (eventSystem) eventSystem.enabled = b;
        }
    }
}